package com.corpgovernment.common.ticket;

import com.corpgovernment.common.utils.HttpUtils;
import com.corpgovernment.redis.cache.RedisUtils;
import com.ctrip.corp.obt.generic.utils.JsonUtils;
import com.fasterxml.jackson.core.type.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Optional;

/**
 * @author ldma
 * @date 2023/12/27
 */
@Component
@Slf4j
public class TicketUtils {

    @Value("${ticketUrl:}")
    private String ticketUrl;

    @Autowired
    private RedisUtils redisUtils;

    public String getTicket(String supplierCode, String appKey, String appSecurity) {
        String key = "ticket:" + supplierCode + ":" + appKey;
        String ticket = redisUtils.getCache(key, String.class);
        if (StringUtils.isNotBlank(ticket)) {
            log.info("获取ticket成功。ticket={} appKey={} appSecurity={}", ticket, appKey, appSecurity);
            return ticket;
        }
        Optional<UrlDo> urlDo = Optional.ofNullable(JsonUtils.parse(ticketUrl, new TypeReference<Map<String, UrlDo>>() {}).get(supplierCode));
        TicketReqDto ticketReqDto = new TicketReqDto(appKey, appSecurity);
        TicketRespDto ticketRespDto = null;
        try {
            ticketRespDto = JsonUtils.parse(HttpUtils.doPostJSON(supplierCode, "获取Ticket", urlDo.map(UrlDo::getUrl).orElse(""), JsonUtils.toJsonString(ticketReqDto)), TicketRespDto.class);
        } catch (Exception e) {
            log.error("获取Ticket失败", e);
        }
        if (ticketRespDto == null) {
            return null;
        }
        // 塞入缓存，设置过期时间为1小时
        try {
            redisUtils.setCache(key, ticketRespDto.getTicket(), urlDo.map(UrlDo::getExpireTime).orElse(3600));
        } catch (Exception e) {
            log.error("设置Ticket缓存失败", e);
        }
        log.info("获取ticket成功。ticket={} appKey={} appSecurity={}", ticket, appKey, appSecurity);
        return ticketRespDto.getTicket();
    }

}
